<?php

/**
 * @author lebangan
 * @copyright 2010
 * Script for update and delete from solr data when solo DB is changed.
 */
/* Edit by NganLB
include_once("Service.php");
include_once("Document.php");
include_once("Response.php");
include_once("Service/Balancer.php");
*/

require_once("solrAPI/Service.php");
require_once("solrAPI/Document.php");
require_once("solrAPI/Response.php");
require_once("log4php/Logger.php");
require_once('config.php');

$end_getdeleteID_function = 0;
$start_getdeleteID_function = 0;
$end_getUpdateRecord_function = 0;
$start_getUpdateRecord_function = 0;
$end_update_solr = 0;
$start_update_solr = 0;

// declare fields in table
$list_fields = array(
  'id',
  'product_id',
  'sku',
  'category_id',
  'category_name',
  'parent_id',
  'name',
  'price',
  'price_vnd',
  'price_old',
  'currency',
  'quantity',
  'origin',
  'vat',
  'quality',
  'state_product',
  'shipping',
  'warranty',
  'content_more',
  'description',
  'fulltext',
  'images',
  'images_other',
  'extra_fields',
  'extra_fields_search',
  'published',
  'publish_up',
  'publish_down',
  'created_by_user',
  'created_by_user_name',
  'modify_by_user',
  'modify_by_user_name',
  'modify_date',
  'ordering',
  'date',
  'is_auth_solo',
  'auth_start_date',
  'auth_end_date',
  'promotion_id',
  'crawl',
  'url_crawl',
  'is_shop_vip',
  'shop_vip_start_date',
  'shop_vip_end_date',
  'province_id',
  'province_name',
  'shop_name'
);

Logger::configure('log4php.properties');

//date_default_timezone_set('Asia/Bangkok');
$start_code = getMicrotime();
//Intial Logger context
$logger = Logger::getLogger("Solr_Update_soProducts_product_classified");

//connect to DB
$conn = mysql_connect(DB_MASTER_SERVER,DB_MASTER_USER,DB_MASTER_PASSWORD) or die ("not connect to DB");
if (!$conn) {
	$logger->error('Could not connect: ' . mysql_error($conn));
    die('Could not connect: ');
}
mysql_query ("SET NAMES 'UTF8'",$conn);

function getMicrotime()
{
	$mtime = explode (' ',microtime());
	return (double) $mtime[0] + $mtime[1];
}

function getTimeTaken($endTime, $startTime)
{
	return number_format(($endTime - $startTime),4);
}

$db = mysql_select_db(DB_MASTER_NAME,$conn) or die ("Non DB exist");
if(!$db) {
	$logger->error('Non DB exist'. mysql_error($conn));
	die('Non DB exist');
}

// select id from so_productsClassifieds_temp table
function getIdProductTmp(){
    $arr = array();
    $query = "SELECT * FROM so_products_classified_temp";
    $result = mysql_query($query);
    while ($row = mysql_fetch_array($result)){
        $arr[]=$row;
    }
    return $arr;
}

// select record from so_products_classified table
function getProductClassified($id){
    $query = "SELECT * FROM so_products_classified WHERE id = $id";
    $result = mysql_query($query);
    if (mysql_num_rows($result) == 1){
        $row = mysql_fetch_array($result);        
        return $row;
    }
    else{
        return 0;
    }            
}

// delete record from so_productsClassifieds_temp
function delProductClassified($count){
    $queryDelete = "DELETE FROM so_products_classified_temp ORDER BY action_time LIMIT $count";    
    mysql_query($queryDelete); 
}

//main script works with solr data
    //set solr service
    $solr = new Apache_Solr_Service(SOLR_SERVER,SOLR_PORT,SOLR_PATH_PRODUCTS_CLASSIFIED); 
    if ($solr->ping()){
        //$solr->deleteByQuery('*:*');        
        $listRecord = getIdProductTmp();
        $count = count($listRecord);
        for ($i=0;$i<$count;$i++){
            if ($listRecord[$i]['action'] != 0){ // if action is insert or update
              	$start_getUpdateRecord_function = getMicrotime();
                $val = getProductClassified($listRecord[$i]['id']);
                if ($val != 0){ // if there's an record in DB 
                    $document = new Apache_Solr_Document();
                    for($j=0;$j<count($list_fields);$j++){
                        //echo $list_fields[$j].":".$val[$list_fields[$j]]."<br>";
                        if (($val[$list_fields[$j]] == null)||($val[$list_fields[$j]] == "")){
                            $val[$list_fields[$j]] = '0';
                        }
                        $document->addField($list_fields[$j], $val[$list_fields[$j]]);
                    }
                    $solr->addDocument($document,true);
                }
                else
                    $logger->warn("product-classified id: " .$listRecord[$i]['id'] ."  doesn't exist in DB");
               	$end_getUpdateRecord_function = getMicrotime();
            }
            else { // action is delete
                $start_getdeleteID_function = getMicrotime();
                $solr->deleteById($listRecord[$i]['id']);
                $end_getdeleteID_function = getMicrotime();
            }
        }
        delProductClassified($count); // delete fields which were selected by getIdProductTmp function
    	try {
        	$start_update_solr = getMicrotime();
    		$solr->commit();
        	$end_update_solr = getMicrotime();
    	} 
        catch (Exception $e) {
    		$logger->error('Can not update to Solr' . $e->getMessage());
    	}
    }
    else
        $logger->error("error to connect Solr Server");

    mysql_close($conn);
    $end_code = getMicrotime();
    $logger->info("Total time taken:" . getTimeTaken($end_code, $start_code) . " secs");
    $logger->info("Get deleted product ID :" . getTimeTaken($end_getdeleteID_function, $start_getdeleteID_function) . " secs");
    $logger->info("Get products Updated :" . getTimeTaken($end_getUpdateRecord_function, $start_getUpdateRecord_function) . " secs");
    $logger->info("Update to Solr :". getTimeTaken($end_update_solr, $start_update_solr) . " secs");

?>